import pino from 'pino';
import { env } from '../env';
import path from 'path';
import fs from 'fs';

const STACKTRACE_OFFSET = 2;
const LINE_OFFSET = 7;
const {
  symbols: { asJsonSym },
} = pino;

function traceCaller(pinoInstance: any): pino.Logger {
  const get = (target: pino.Logger, name: string | symbol) => {
    if (name === asJsonSym) {
      return asJson;
    }
    // 确保 name 是 pino.Logger 的已知属性
    return target[name as keyof pino.Logger];
  };

  function asJson(this: any, ...args: [Record<string, any>, ...any[]]) {
    args[0] = args[0] || Object.create(null);
    args[0].caller = Error()
      .stack?.split('\n')
      .filter(
        (s) =>
          !s.includes('node_modules/pino') && !s.includes('node_modules\\pino'),
      )
      [STACKTRACE_OFFSET].substring(LINE_OFFSET)
      .replace(env.ROOT_DIR, '');
    return pinoInstance[asJsonSym].apply(this, args);
  }

  return new Proxy(pinoInstance, { get });
}

const logFilePath = path.join(__dirname, '../logfile.log');
const logDir = path.dirname(logFilePath);
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

const logStream = fs.createWriteStream(logFilePath, { flags: 'a' });

export const logger = traceCaller(
  pino(
    {
      level: 'debug',
      transport: {
        target: 'pino-pretty',
        options: {
          colorize: true,
          translateTime: true,
        },
      },
    },
    logStream,
  ),
);

// 测试日志
logger.debug('This is a debug message');
logger.info('This is an info message');
